package com.lcc.lynx.jdbc.qw;

import com.lcc.lynx.common.utils.ReflectUtil;
import com.lcc.lynx.jdbc.util.JDBCReflectUtil;
import lombok.Getter;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MyResultHandler<R> implements ResultHandler<Map<String, Object>> {
    private final Class<R> resultType;
    @Getter
    private final List<R> results = new ArrayList<>();

    public MyResultHandler(Class<R> resultType) {
        this.resultType = resultType;
    }

    @Override
    public void handleResult(ResultContext<? extends Map<String, Object>> resultContext) {
        Map<String, Object> resultObject = resultContext.getResultObject();
        if(resultObject == null){
            results.add(null);
        }else if(resultType == Map.class){
            results.add((R) resultObject);
        }else {
            results.add(JDBCReflectUtil.mapToObj(resultObject, resultType));
        }
    }

}
